package com.itheima.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.codehaus.jettison.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class SMSUtil {

    private static final String REGION_ID = "cn-hangzhou";
    private static final String ACCESS_KEY_ID = "LTAI4G7CvvSvocmukbijjiWa";
    private static final String ACCESS_KEY_SECRET = "YScT9S8jplhZwG8slME3yH6V6zFwM3";
    private static final String SIGN_NAME = "创智健康系统";
    private static final String TEMPLATE_VALID_CODE = "SMS_205468650";//短信校验码模板

    public static String sendSmsValidCode(String telephone){
        Map param = new HashMap();
        String code = generatorCode(4);
        param.put("code",code);
        if(sendSms(telephone,TEMPLATE_VALID_CODE,param)){
            return code;
        }
        return null;
    }

    public static String generatorCode(Integer smsBit){
        if(smsBit == null){
            throw new RuntimeException("短信位数未指定");
        }
        if(smsBit != 4 && smsBit != 6){
            throw new RuntimeException("短信位数只能是4或6");
        }
        if(smsBit == 4){//4位
            return String.valueOf(new Random().nextInt(9000-1) + 1000);
        }else{//6位
            return String.valueOf(new Random().nextInt(900000-1) + 100000);
        }
    }

    public static boolean sendSms(String telephone, String templateCode, Map param) {
        DefaultProfile profile = DefaultProfile
                .getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", REGION_ID);
        request.putQueryParameter("PhoneNumbers", telephone);
        request.putQueryParameter("SignName", SIGN_NAME);
        request.putQueryParameter("TemplateCode", templateCode);
        JSONObject jsonObject = new JSONObject(param);
        System.out.println("param:" + jsonObject.toString());
        request.putQueryParameter("TemplateParam", jsonObject.toString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject result = new JSONObject(response.getData());
            if("OK".equals(result.getString("Code"))){
                return true;
            }else{
                System.out.println("发送短信失败:" + response.getData());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
